package com.example.wordssample;

import android.content.Context;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.wordssample.DAO.WordDao;
import com.example.wordssample.Entity.Word;

@Database(entities = {Word.class}, version = 1, exportSchema = false)
public abstract class WordRoomDatabase extends RoomDatabase {
    private  static  RoomDatabase.Callback sRoomDatabaseCallback=
            new RoomDatabase.Callback(){
                @Override
                public void onOpen(@NonNull SupportSQLiteDatabase db) {
                    super.onOpen(db);
                    new PopulateDbsync(INSTANCE).execute();
                }
            };
            private  static class  PopulateDbsync extends AsyncTask<Void,Void,Void>{

        private final  WordDao mDao;
        String[] words={"dolphin","crocodile","cobra"};
        PopulateDbsync(WordRoomDatabase db){
            mDao=db.wordDao();
        }

                @Override
                protected Void doInBackground(Void... params) {
                    if (mDao.getAnyWord().length < 1) {
                    for (int i=0;i<=words.length-1 ;i++){
                        Word word =new Word(words[i]);
                        mDao.insert(word);
                    }}
                    return  null;
                }
            }

    public abstract WordDao wordDao();
    public static WordRoomDatabase INSTANCE;
    public static WordRoomDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (WordRoomDatabase.class) {
                if (INSTANCE == null) {
                    // Create database here
                    // Create database here
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            WordRoomDatabase.class, "word_database")
                            .fallbackToDestructiveMigration()
                            .addCallback(sRoomDatabaseCallback)

                            .build();

                }
            }
        }
        return INSTANCE;
    }

}
